package com.anxinr.aop;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletMapping;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @author : anxinr
 * @date : 2022/10/10 17:12
 */
@Slf4j
@Aspect
@Component
public class GlobalLogAop {
    @Autowired
    private HttpServletRequest request ;
    @Pointcut("execution(* com.anxinr.interceptor.StudyInterceptor.preHandle(..))")
    public void printLog(){};

    /**
     * 在方法执行之前
     * 添加拦截日志
     * @author anxinr
     */
    @Before("printLog()")
    public void beforePrintLog() throws Exception {
        // 转换为JSON对象
        if (StringUtils.isBlank(request.getQueryString())){
            StringBuilder stringBuilder = new StringBuilder();
            String line  ;
            BufferedReader reader = request.getReader();
            while (null != (line = reader.readLine())){
                stringBuilder.append(line);
            }
            log.info("请求方法为 -> {} , 请求路径为 -> {}, 请求体信息为 -> {}",request.getMethod(),request.getRequestURL(),JSONObject.parseObject(stringBuilder.toString()));
        }else {
            log.info("请求方法为 -> {} , 请求路径为 -> {}, 请求体信息为 -> {}",request.getMethod(),request.getRequestURL(),request.getQueryString());
        }
    }
}
